package cn.ant.mqHandle.consumer;

import cn.ant.config.RabbitMQConfig;
import cn.ant.entity.MessageSendDTO;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/***
 * 备份消费者类
 * @author Anhui AntLaddie <a href="https://juejin.cn/user/4092805620185316">(掘金蚂蚁小哥)</a>
 * @version 1.0
 **/
@Slf4j
@Component
public class BackupConsumer {

    /***
     * 备份队列消费者接收的消息监听
     */
    @RabbitListener(queues = {RabbitMQConfig.BACKUP_QUEUE}, ackMode = "MANUAL")
    public void backupConsumerTest(@Payload String msgData,
                                   Message message,
                                   Channel channel) throws IOException {
        // 把接收过来的JSON信息转换为对象
        try {
            MessageSendDTO messageSendDTO = JSONObject.parseObject(msgData, MessageSendDTO.class);
            // 队列名称
            String consumerQueue = message.getMessageProperties().getConsumerQueue();
            log.info("备份队列：{}，监听发送过来的数据并处理：{}", consumerQueue, messageSendDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.info("备份消费失败：{}", msgData);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
